<template>
  <div class="bargain-management">
    <h2 class="page-title">我的砍价意向管理</h2>

    <!-- 砍价列表表格 -->
    <el-table :data="bargainList" border stripe style="width: 100%; margin-bottom: 20px;">
      <el-table-column label="砍价ID" prop="bargainId" width="80" align="center" />
      <el-table-column label="设备ID" prop="equipmentId" width="100" align="center" />
      <el-table-column label="原价(元)" prop="originalPrice" width="120" align="center">
        <template #default="scope">{{ scope.row.originalPrice.toLocaleString() }}</template>
      </el-table-column>
      <el-table-column label="意向价格(元)" prop="intentionPrice" width="120" align="center">
        <template #default="scope">{{ scope.row.intentionPrice.toLocaleString() }}</template>
      </el-table-column>
      <el-table-column label="砍价状态" prop="bargainStatus" width="100" align="center">
        <template #default="scope">
          <!-- 补充 bargainStatus === 2 已拒绝的处理 -->
          <el-tag 
            :type="scope.row.bargainStatus === 1 ? 'success' : 
                  scope.row.bargainStatus === 2 ? 'danger' : 'info'"
          >
            {{ scope.row.bargainStatus === 1 ? '已回复' : 
               scope.row.bargainStatus === 2 ? '已拒绝' : '待回复' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="卖家回复" prop="sellerReply" align="center" />
      <el-table-column label="创建时间" prop="createTime" width="180" align="center">
        <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="回复时间" prop="replyTime" width="180" align="center">
        <template #default="scope">{{ scope.row.replyTime ? formatDate(scope.row.replyTime) : '暂无' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.bargainId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <el-empty v-if="bargainList.length === 0" description="暂无砍价意向记录" />

    <!-- 美化后的修改砍价对话框：添加 align-center 实现居中 -->
    <el-dialog 
      title="修改砍价意向" 
      v-model="isEditDialogOpen" 
      width="550px" 
      :close-on-click-modal="false"
      :show-close="false"
      class="custom-edit-dialog"
      align-center 
    >
      <!-- 对话框头部（自定义关闭按钮） -->
      <div class="dialog-header">
        <h3 class="dialog-title">修改砍价意向</h3>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          class="close-btn"
          @click="isEditDialogOpen = false"
        />
      </div>

      <!-- 表单内容 -->
      <el-form 
        :model="updateKanData" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="110px"
        class="edit-form"
      >
        <!-- 不可修改项组 -->
        <div class="form-group">
          <div class="group-title">基础信息（不可修改）</div>
          <div class="form-row">
            <el-form-item label="设备ID" prop="equipmentId" class="form-item">
              <el-input 
                v-model="updateKanData.equipmentId" 
                disabled 
                placeholder="设备ID不可修改"
                class="disabled-input"
              />
            </el-form-item>
            <el-form-item label="原价(元)" prop="originalPrice" class="form-item">
              <el-input 
                v-model="updateKanData.originalPrice" 
                disabled 
                placeholder="原价不可修改"
                class="disabled-input"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 可修改项组 -->
        <div class="form-group">
          <div class="group-title">修改信息</div>
          <el-form-item label="意向价格(元)" prop="intentionPrice" class="form-item">
            <el-input 
              v-model.number="updateKanData.intentionPrice" 
              type="number" 
              min="1" 
              placeholder="请输入意向价格"
              class="custom-input"
            />
            <div class="form-hint">价格不能低于1元，建议不高于原价</div>
          </el-form-item>
          
          <el-form-item label="砍价备注" prop="bargainRemark" class="form-item">
            <el-input 
              v-model="updateKanData.bargainRemark" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入砍价备注（如成交要求、自提说明等）"
              class="custom-textarea"
            />
            <div class="form-hint">备注最多200个字符，清晰描述您的需求可提高成交率</div>
          </el-form-item>
        </div>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="text" 
            class="cancel-btn"
            @click="isEditDialogOpen = false"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            class="confirm-btn"
            @click="submitEdit"
          >
            <i class="el-icon-check mr-1"></i> 确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, unref } from 'vue';
import axios from 'axios';
import { useCounterStore } from '@/stores/counter';
import { 
  ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, 
  ElInput, ElMessage, ElMessageBox, ElTag, ElEmpty, ElIcon 
} from 'element-plus';
import { Close, Check } from '@element-plus/icons-vue';
import 'element-plus/dist/index.css';

// Pinia状态
const counterStore = useCounterStore();

// 表格数据（处理后的列表）
const bargainList = ref([]);
// 修改对话框显示状态
const isEditDialogOpen = ref(false);
// 表单ref（用于验证）
const editFormRef = ref(null);
// 修改表单数据
const updateKanData = reactive({
  bargainId: '',
  userId: '',
  equipmentId: '',
  originalPrice: '',
  intentionPrice: '',
  bargainRemark: ''
});

// 修改表单验证规则
const editRules = reactive({
  intentionPrice: [
    { required: true, message: '请输入意向价格', trigger: 'blur' },
    { type: 'number', min: 1, message: '价格不能小于1', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value > updateKanData.originalPrice) {
          callback(new Error('意向价格不能高于原价'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  bargainRemark: [
    { required: true, message: '请输入砍价备注', trigger: 'blur' },
    { max: 200, message: '备注不能超过200个字符', trigger: 'blur' }
  ]
});

// 获取当前用户砍价列表
const getAllKanByUserId = async () => {
  try {
    const userId = counterStore.userId;
    if (!userId) {
      ElMessage.warning('用户未登录，请先登录');
      return;
    }
    
    console.log('用户ID:', userId);
    const response = await axios.get(`/eduservice/bargainintention/getBargainIntentionListByUserId/${userId}`);
    
    console.log('响应数据:', response.data);
    if (response.data.success && response.data.data?.list) {
      bargainList.value = response.data.data.list;
      console.log('获取到的砍价列表:', bargainList.value);
    } else {
      bargainList.value = [];
      ElMessage.warning('获取砍价列表失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('获取砍价列表出错:', error);
    bargainList.value = [];
    ElMessage.error('网络错误，获取砍价列表失败');
  }
};

// 处理修改按钮点击
const handleEdit = (row) => {
  // 复制当前行数据到修改表单
  Object.assign(updateKanData, {
    bargainId: row.bargainId,
    userId: row.userId,
    equipmentId: row.equipmentId,
    originalPrice: row.originalPrice,
    intentionPrice: row.intentionPrice,
    bargainRemark: row.bargainRemark
  });
  // 打开对话框
  isEditDialogOpen.value = true;
};

// 提交修改
const submitEdit = async () => {
  try {
    // 表单验证
    const formRef = unref(editFormRef);
    if (!formRef) return;
    await formRef.validate();

    console.log('提交修改数据:', updateKanData);
    const res = await axios.put(
      '/eduservice/bargainintention/updateBargainIntention',
      updateKanData
    );

    // 根据返回的boolean判断结果
    if (res.data) {
      ElMessage.success('修改成功');
      isEditDialogOpen.value = false;
      // 刷新列表
      await getAllKanByUserId();
    } else {
      ElMessage.error('修改失败，请重试');
    }
  } catch (error) {
    console.error('修改砍价出错:', error);
    if (error.name === 'ValidationError') {
      return; // 表单验证失败，不显示错误提示
    }
    ElMessage.error('网络错误，修改失败');
  }
};

// 处理删除按钮点击
const handleDelete = async (bargainId) => {
  try {
    // 确认对话框
    await ElMessageBox.confirm(
      '此操作将永久删除该砍价意向，是否继续？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await axios.delete(`/eduservice/bargainintention/deleteBargainIntention/${bargainId}`);
    console.log('删除响应数据:', response.data);
    
    if (response.data.success) {
      ElMessage.success('删除成功');
      // 刷新列表
      await getAllKanByUserId();
    } else {
      ElMessage.error('删除失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('删除砍价出错:', error);
    // 如果是取消删除，不显示错误提示
    if (error.message !== 'cancel') {
      ElMessage.error('网络错误，删除失败');
    }
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 页面挂载时获取列表
onMounted(() => {
  getAllKanByUserId();
});
</script>

<style scoped>
.bargain-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1989fa;
}

.el-table {
  --el-table-header-text-color: #333;
  --el-table-row-hover-bg-color: #f5fafe;
}

.el-button + .el-button {
  margin-left: 8px;
}

/* 自定义对话框样式 */
.custom-edit-dialog {
  --el-dialog-border-radius: 12px;
  --el-dialog-box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-title {
  font-size: 16px;
  font-weight: 600;
  color: #1989fa;
  margin: 0;
}

.close-btn {
  color: #999;
  font-size: 18px;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #1989fa;
}

/* 表单样式 */
.edit-form {
  padding: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.group-title {
  font-size: 14px;
  font-weight: 500;
  color: #666;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #1989fa;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-item {
  margin-bottom: 16px;
  width: 100%;
}

/* 不可修改输入框 */
.disabled-input {
  background-color: #fafafa;
  border-color: #e0e0e0;
  color: #999;
  border-radius: 6px;
}

/* 自定义输入框 */
.custom-input {
  border-radius: 6px;
  transition: all 0.3s;
}

.custom-input:focus {
  border-color: #1989fa;
  box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.1);
}

/* 文本域 */
.custom-textarea {
  border-radius: 6px;
  resize: none;
  transition: all 0.3s;
}

.custom-textarea:focus {
  border-color: #1989fa;
  box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.1);
}

/* 表单提示 */
.form-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  line-height: 1.4;
}

/* 底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.cancel-btn {
  color: #666;
  transition: color 0.3s;
}

.cancel-btn:hover {
  color: #1989fa;
}

.confirm-btn {
  background-color: #1989fa;
  border-color: #1989fa;
  border-radius: 6px;
  padding: 8px 24px;
  transition: all 0.3s;
}

.confirm-btn:hover {
  background-color: #0a7cff;
  border-color: #0a7cff;
  transform: translateY(-1px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .custom-edit-dialog {
    width: 90% !important;
  }
}
</style>